package com.cgsd.heyu.ui;


import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.android.library.adapter.OnViewHelper;
import com.android.library.adapter.ViewHelper;
import com.android.library.image.GlideUtil;
import com.android.library.utils.AppManager;
import com.android.library.utils.BeanUtils;
import com.android.library.utils.StringUtils;
import com.android.library.utils.ToastHelper;
import com.android.library.wedgets.TitleBarView;
import com.cgsd.heyu.R;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.ExceptionHandler;
import com.cgsd.heyu.http.GlobalErrorMessage;
import com.cgsd.heyu.presenter.BasePresenter;
import com.cgsd.heyu.presenter.BaseView;
import com.cgsd.heyu.ui.home.MainActivity;
import com.cgsd.heyu.ui.home.SplashActivity;
import com.cgsd.heyu.ui.login.LoginActivity;
import com.cgsd.heyu.utils.StatusBarUtil;
import com.cgsd.heyu.widgets.CommonProgressDialog;
import com.cgsd.heyu.widgets.ErrorCustomView;
import com.cgsd.heyu.widgets.dialog.ForceConfirmDialog;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;


/**
 * @author xiaoxing
 * Created by Administrator on 2018/4/26.
 * 活动消息列表
 */

public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity implements BaseView<T> {
    protected int page = 1;
    protected T mPresenter;
    private CommonProgressDialog mSubmitDialog;
    protected TitleBarView mTitleBar;
    protected FrameLayout viewContent;
    protected String TAG = getClass().getSimpleName() + "\n";
    /**
     * 默认布局
     **/
    protected View mErrorView;
    /**
     * 业务逻辑布局
     */
    protected View mContentView;
    /**
     * 默认错误页面
     */
    protected ErrorCustomView mErrorCustomView;
    /**
     * 确认退出弹窗
     */
    private ForceConfirmDialog confirmDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            Intent intent = new Intent(this, SplashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }
        //activity统一管理
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.activity_base);
        init();
        setStatusBar();
        initView();
        initData();

        if (isRegisterEventBus()) {
            registerEventBus(this);
        }
    }

    /**
     * base公共初始化参数
     */
    protected void init() {
        //统一加载错误和主页面处理
        viewContent = findViewById(R.id.view_content);
        if (useCustomLayout() == null) {
            mErrorView = LayoutInflater.from(this).inflate(R.layout.layout_timeout, viewContent, false);
            mErrorCustomView = mErrorView.findViewById(R.id.mErrorView);
        } else {
            mErrorView = useCustomLayout();
        }
        mContentView = LayoutInflater.from(this).inflate(getLayoutId(), viewContent, false);
        viewContent.addView(mContentView);
        viewContent.addView(mErrorView);
        mErrorView.setVisibility(View.GONE);

        loadSuccess();
        //标题栏
        mTitleBar = findViewById(R.id.title_bar);
        if (mTitleBar != null) {
            mTitleBar.setTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
                @Override
                public void leftClick() {
                    clickLeft();
                }

                @Override
                public void rightClick() {
                    clickRight();
                }
            });
        }
    }

    /**
     * 点击titleBar左边
     */
    protected void clickLeft() {
        finish();
    }

    /**
     * 点击titleBar最右边
     */
    protected void clickRight() {

    }

    protected void setStatusBar() {
        StatusBarUtil.setBarColor(this, R.color.white);
    }

    /**
     * 布局xml文件
     *
     * @return 资源id
     */
    protected abstract int getLayoutId();

    /**
     * 初始化view
     */

    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 是否显示标题栏
     *
     * @param isShow {@link MainActivity}
     */
    protected void isShowToolBar(boolean isShow) {
        if (isShow) {
            mTitleBar.setVisibility(View.VISIBLE);
        } else {
            mTitleBar.setVisibility(View.GONE);
        }
    }

    /**
     * 是否已经注册过
     *
     * @param subscribe
     * @return
     */
    public boolean isEventBusRegistered(Object subscribe) {
        return EventBus.getDefault().isRegistered(subscribe);
    }

    /**
     * 注册EventBus
     *
     * @param subscribe
     */
    public void registerEventBus(Object subscribe) {
        if (!isEventBusRegistered(subscribe)) {
            EventBus.getDefault().register(subscribe);
        }
    }

    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //友盟统计
        MobclickAgent.onResume(this);
        GlideUtil.resumeRequests(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //友盟统计
        MobclickAgent.onPause(this);
        GlideUtil.pauseRequest(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterEventBus(this);
        AppManager.getAppManager().finishActivity(this);
    }


    /**
     * 提交数据统一加载进度条
     *
     * @param msg
     */
    protected void showCommonSubmitDialog(String msg) {
        if (mSubmitDialog == null) {
            mSubmitDialog = new CommonProgressDialog(this, R.style.dialog_common_loading, StringUtils.isNotEmpty(msg) ? msg : "加载中...");
        }
        mSubmitDialog.show();
    }

    /**
     * 提交数据统一加载进度条
     */
    protected void showCommonSubmitDialog() {
        showCommonSubmitDialog("");
    }

    /**
     * 关闭提交数据统一加载进度条
     */
    protected void dismissCommonSubmitDialog() {
        if (mSubmitDialog != null && mSubmitDialog.isShowing()) {
            mSubmitDialog.dismiss();
        }
    }

    /**
     * 反注册EventBus
     *
     * @param subscribe
     */
    public void unregisterEventBus(Object subscribe) {
        if (isEventBusRegistered(subscribe)) {
            EventBus.getDefault().unregister(subscribe);
        }
    }

    /**
     * 实例化对应layoutId的view同时生成ViewHelper帮助类
     *
     * @param group    可为null
     * @param layoutId
     * @param listener
     * @return
     */
    protected View getHelperView(ViewGroup group, int layoutId, OnViewHelper listener) {
        ViewHelper helper = new ViewHelper(getLayoutInflater().inflate(layoutId, group == null ? null : group instanceof RecyclerView ? (ViewGroup) group.getParent() : group, false));
        if (listener != null) {
            listener.help(helper);
        }
        return helper.getItemView();
    }


    /******************-----------------------------------------同意错误处理（提示和页面显示）------------------------------------------------***********/

    /**
     * 处理error
     *
     * @param errorMessage
     */
    private void handleErrorAction(ErrorMessage errorMessage) {
        if (this != AppManager.getAppManager().currentActivity()) {
            return;
        }
        //需要登录
        if (errorMessage.getCode() == GlobalErrorMessage.ErrorCode.ERROR_CODE_5557
                || errorMessage.getCode() == GlobalErrorMessage.ErrorCode.ERROR_CODE_5558
                || errorMessage.getCode() == GlobalErrorMessage.ErrorCode.ERROR_CODE_5556) {
            showConfirmDialog(errorMessage.getMessage());
        } else if (!BeanUtils.isEmpty(errorMessage) &&
                errorMessage.getCode() != ExceptionHandler.Error.UNKNOWN) {
            ToastHelper.showDefaultToast(errorMessage.getMessage());
        }
    }

    /**
     * 显示退出弹窗
     */
    protected void showConfirmDialog(String content) {
        if (confirmDialog == null) {
            confirmDialog = new ForceConfirmDialog(this);
            confirmDialog.setTitle(content);
            confirmDialog.setTvButton(getString(R.string.got_it));
            confirmDialog.setDialogListener(new ForceConfirmDialog.DialogListener() {
                @Override
                public void confirm() {
                    confirmDialog.dismiss();
                    gotoLogin();
                }
            });
        }
        confirmDialog.show();
    }

    private void gotoLogin() {
        LoginActivity.actionStart(this);
    }

    /**
     * 页面加载中
     */
    protected void showLoading() {
        mErrorView.setVisibility(View.VISIBLE);
        mContentView.setVisibility(View.GONE);
        mErrorCustomView.showLoading();
    }

    /**
     * 页面加载完成
     */
    protected void loadSuccess() {
        mErrorView.setVisibility(View.GONE);
        mContentView.setVisibility(View.VISIBLE);
    }

    /**
     * 页面数据为空
     */
    protected void showEmptyView() {
        mErrorView.setVisibility(View.VISIBLE);
        mContentView.setVisibility(View.GONE);
        mErrorCustomView.showEmpty();
    }

    /**
     * 页面数据为空
     *
     * @param drawableResId
     */
    protected void showEmptyView(@DrawableRes int drawableResId, String title) {
        mErrorView.setVisibility(View.VISIBLE);
        mContentView.setVisibility(View.GONE);
        mErrorCustomView.showEmpty(drawableResId, title);
    }

    /**
     * 网络错误
     */
    protected void showNetworkError() {
        mErrorView.setVisibility(View.VISIBLE);
        mContentView.setVisibility(View.GONE);
        mErrorCustomView.showNetworkError();
    }

    /**
     * 网络错误
     */
    protected void showNetworkError(@DrawableRes int drawableResId, String title) {
        mErrorView.setVisibility(View.VISIBLE);
        mContentView.setVisibility(View.GONE);
        mErrorCustomView.showNetworkError(drawableResId, title);
    }

    /**
     * Toast提示
     */
    protected void showToast(String content) {
        ToastHelper.showDefaultToast(content);
    }

    /**
     * 自定义错误页面
     * 默认错误页面 {@link ErrorCustomView}
     *
     * @return
     */
    protected View useCustomLayout() {
        return null;
    }

    /******************-----------------------------------------公共View接口回调------------------------------------------------***********/
    @Override
    public void setPresenter(T presenter) {
        mPresenter = BeanUtils.checkNotNull(presenter);
    }

    @Override
    public void setErrorMessage(ErrorMessage error) {
        dismissCommonSubmitDialog();
        handleErrorAction(error);
    }
}
